<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <!-- 顶部工具栏 -->
        <PageTools>
          <el-button slot="before" type="primary" max-height="40px" @click="dialogShow = true">添加客户</el-button>
          <template slot="after">
            <!-- <div style="width: 600px"> -->
            <el-input v-model="selectQuery.name_contains" placeholder="请输入客户关键字" class="input-with-select" @keyup.enter.native="selectFn">
              <el-select slot="prepend" v-model="selectQuery.agent" placeholder="全部经纪">
                <el-option v-for="item in agentList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-button slot="append" size="mini" icon="el-icon-download" @click="exportDataFn" />
            </el-input>
            <el-button type="primary" style="margin-left:5px" @click="selectFn">筛选</el-button>
            <!-- </div> -->
          </template>
        </PageTools>

        <!-- 放置表格和分页 -->
        <div v-loading="loading" class="main" element-loading-text="拼命加载中">
          <el-table border :data="clientList" height="calc(100vh - 247px)">
            <el-table-column label="图片" sortable="" prop="image" width="80" max-height="280px">
              <template v-slot="{row}">
                <el-image
                  style="width: 50px; height: 50px; border-radius: 10%"
                  :src="row.image"
                /></template>
            </el-table-column>
            <el-table-column label="名称" sortable="" prop="name" />
            <el-table-column label="邮箱" sortable="" prop="email" />
            <el-table-column label="电话" sortable="" prop="phone" />
            <el-table-column label="经纪" sortable="" prop="agent.name" />
            <el-table-column label="微信" sortable="" prop="wechat" />
            <el-table-column label="介绍" sortable="" prop="desc" />
            <el-table-column label="操作" sortable="" fixed="right" width="280">
              <template v-slot="{row}">
                <!-- :disabled="checkPermission('POINT-USER-UPDATE')" -->
                <el-button type="primary" size="small" @click="edit(row.id)">编辑</el-button>
                <el-button type="danger" size="small" @click="del(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="total, sizes, prev, pager, next, jumper" :page-siez="clientQuery._limit" :total="clientTotal" :page-sizes="[4, 6, 8, 14]" :current-page="curPage" @size-change="handleSizeChange" @current-change="changePage" />
        </el-row>
      </el-card>

      <!-- 放置编辑、新增客户弹层 -->
      <AddClient ref="addClient" :dialog-show.sync="dialogShow" :agent-list="agentList" />
    </div>
  </div>
</template>

<script>
import AddClient from '@/views/clients/component/add-clients.vue'
import { delClient, getClientList, getClientNum } from '@/api/client'
import { getAgents } from '@/api/agents'
import { export_json_to_excel } from '@/vendor/Export2Excel'
export default {
  components: { AddClient },
  data() {
    return {
      curPage: 1,
      clientTotal: 0,
      dialogShow: false,
      clientList: [],
      agentList: [],
      clientId: '',
      clientQuery: {
        // 获取客户列表请求参数
        _limit: 4, // 获取的最大条数
        _start: 0 // 开始获取的位置
      },
      selectQuery: {
        name_contains: '', // 模糊搜索名称
        agent: '' // 筛选的经纪人id
      },
      input: '',
      select: '',
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false
    }
  },
  created() {
    this.getClientNum()
    this.getAgentsList()
    this.getClientList()
  },
  methods: {
    // 改变每页显示数量时触发 接收的参数是 每页显示的数量
    handleSizeChange(pagesize) {
      this.clientQuery._limit = pagesize
      this.getClientList()
    },
    // 切换页数时触发
    changePage(newPage) {
      this.curPage = newPage
      this.clientQuery._start = (newPage - 1) * this.clientQuery._limit
      this.getClientList()
    },
    // 获取客户总数
    async getClientNum(params) {
      this.clientTotal = await getClientNum(params)
    },
    // 获取经纪列表
    async getAgentsList() {
      this.agentList = await getAgents()
      this.agentList.unshift({ name: '全部经纪', id: '' })
    },
    // 获取客户列表
    async getClientList() {
      this.loading = true
      this.clientList = await getClientList(this.clientQuery)
      this.loading = false
    },
    // 筛选客户
    async selectFn() {
      this.curPage = 1
      // 如果筛选条件 有经纪人  参数就是默认的 this.clientQuery +this.selectQuery
      if (this.selectQuery.agent) {
        this.clientQuery = { _limit: this.clientQuery._limit, _start: 0, ...this.selectQuery }
        // 如果没有经纪人但是有客户名 参数就只传入name_contains  要不然会搜不到
      } else if (!this.selectQuery.agent && this.selectQuery.name_contains) {
        this.clientQuery = { _limit: this.clientQuery._limit, _start: 0, name_contains: this.selectQuery.name_contains }
        // 如果是两个筛选参数都没有 就只传入默认参数
      } else if (!this.selectQuery.agent && !this.selectQuery.name_contains) {
        this.clientQuery = { _limit: this.clientQuery._limit, _start: 0 }
      }
      this.clientList = await getClientList(this.clientQuery)
      // 请求到客户列表后 需要将total更新
      this.updateNum()
      this.$message.success('筛选成功！')
    },
    // 弹出编辑客户弹层
    async edit(id) {
      this.clientId = id
      this.dialogShow = true// 弹层显示要在拿到客户详情之前 要不然会拿不到弹层的this.$refs
      await this.$refs.addClient.getClientById(id)
    },
    // 删除客户 666
    async del(id) {
      try {
        await this.$confirm('确认删除改客户吗？')
        await delClient(id)
        if (this.clientList.length === 1) {
          this.clientQuery._start = this.clientQuery._start - this.clientQuery._limit
        }
        this.updateNum()
        this.getClientList()
        this.$message.success('删除客户成功！')
      } catch (error) {
        console.log(error)
      }
    },
    updateNum() {
      if (!this.selectQuery.agent && !this.selectQuery.name_contains) {
        this.getClientNum() // 两个筛选条件都没有 就获取所有客户数量
      } else if (!this.selectQuery.agent) {
        this.getClientNum({ name_contains: this.selectQuery.name_contains }) // 如果没有筛选经纪人 就只把name_contains 当作实参 传入
      } else {
        this.getClientNum(this.selectQuery)
      }
    },
    // #region
    // #region 导出数据为Excel表格
    async exportDataFn() {
      const result = await getClientList(
        { _limit: 99999, _start: 0 }
      )
      console.log(result)

      const res = result.map(item => { // map处理数组数据
        return this.objToArr(item) // 调用函数处理
      })
      console.log(res)
      const header = ['名称', '邮箱', '电话', '微信', '介绍']

      export_json_to_excel({
        header, // []
        data: res // 必须是 [[]] 这样的数据格式
      })
    },
    // #endregion
    objToArr(item) { // 处理成想要的数据格式
      const dic = { // 字段字典
        名称: 'name',
        邮箱: 'email',
        电话: 'phone',
        微信: 'wechat',
        介绍: 'desc'
      }
      const arr = [] // 声明一个空数组
      for (const key in dic) {
        arr.push(item[dic[key]]) // 添加进数组
      }
      return arr
    }
    // #endregion
  }
}
</script>

<style scoped lang="scss">

::v-deep .main {
  padding-top: 20px;
  padding-bottom: 20px;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
::v-deep .top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.el-button--primary {
  max-height: 40px;
}

::v-deep .el-input-group__append,
::v-deep .el-input-group__prepend  {
  background-color: #fff;
  div.el-select .el-input__inner{
    width: 110px;
    color: #000;
  }
  div.el-select .el-input__inner::-webkit-input-placeholder {
    color: #000;
  }
}
::v-deep .el-input {
  .el-button span,
  .el-icon-notebook-2 {
    color: #000;
  }
}
</style>
